package ru.narod.amidoriya.app.sushibaramidoriya;

import android.app.*;
import android.content.*;
import android.content.DialogInterface.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
import com.actionbarsherlock.app.*;
import com.actionbarsherlock.view.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import android.content.DialogInterface.OnClickListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.os.AsyncTask;
import org.xmlpull.v1.*;
import java.io.*;
import java.net.*;
import android.net.*;


public class Aktions extends SherlockActivity

{
	Integer seeFlagAktion;
	Integer seeFlagAktiont;
	String seeFlagAktionNew;
	Gallery g;
	
	public GalleryAdapter adapterAktions;
	ArrayList<HashMap<String, String>> dataAktions;
	HashMap<String, String> dgv;
	
	GalleryTask gtask;
	ProgressDialog gdtask;
	String galleryurl, SUB_HOST_A;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aktion_gallery);
		g = (Gallery) findViewById(R.id.galleryaktion);
		SUB_HOST_A = getString(R.string.SUB_HOST_ACTIONS);
		galleryurl = SUB_HOST_A + getString(R.string.app_actions); 
		//xml
		//AsyncTask
		if (isNetworkAvailable()) {
		gtask = new GalleryTask();
		gtask.execute(SUB_HOST_A, galleryurl);
	    } else { 
			Toast.makeText(this, "Нет интернета", Toast.LENGTH_SHORT).show(); 
		}
		
	}		
	class GalleryTask extends AsyncTask<String, Void, Void> { 

		@Override 
		protected void onPreExecute() {   	   
			super.onPreExecute(); 
			
		} 
		@Override 
		protected Void doInBackground(String... urls) {

			try {
				getDataAktionsXml(urls[0],urls[1]);
			
			} catch (InterruptedException e) {
				
			}


			return null; 
		} 
		@Override 
		protected void onPostExecute(Void result) { 
			super.onPostExecute(result);
			g.setAdapter(adapterAktions);
			

		}
		private void getDataAktionsXml(String hub_path,String mgurln) throws InterruptedException {
			dataAktions =  new ArrayList<HashMap<String, String>>();
			////begin get data url
			try {
				URL urld = new URL(mgurln);
				HttpURLConnection urlConnectiond = (HttpURLConnection) urld.openConnection();
				urlConnectiond.setRequestMethod("GET");
				urlConnectiond.setDoOutput(true);
				urlConnectiond.connect(); 
				XmlPullParserFactory parserpull = XmlPullParserFactory.newInstance();
				parserpull.setValidating(false);
				XmlPullParser parserflurl = parserpull.newPullParser();
				InputStream xmlmgurl = urlConnectiond.getInputStream();
				parserflurl.setInput(xmlmgurl, null);

				while (parserflurl.getEventType()!= XmlPullParser.END_DOCUMENT) {
					if (parserflurl.getEventType() == XmlPullParser.START_TAG
						&& parserflurl.getName().equals("action_rest")) {
						dgv = new HashMap<String, String>();
	   					String begin_seedate = parserflurl.getAttributeValue(0);
	   					if (begin_seedate == null) {
	   						begin_seedate = "";
	   					}else {
	   						begin_seedate = parserflurl.getAttributeValue(0);	
	   					}
						String begin_date = parserflurl.getAttributeValue(1);
	   					if (begin_date == null) {
	   						begin_date = "";
	   					}else {
	   						begin_date = parserflurl.getAttributeValue(1);	
	   					}
						String end_date = parserflurl.getAttributeValue(2);
	   					if (end_date == null) {
	   						end_date = "";
	   					}else {
	   						end_date = parserflurl.getAttributeValue(2);	
	   					}
						String action_pic = parserflurl.getAttributeValue(3);
	   					if (action_pic == null) {
	   						action_pic = "";
	   					}else {
	   						action_pic = parserflurl.getAttributeValue(3);	
	   					}
						String filepicPathUrl = "";						
						filepicPathUrl = hub_path + action_pic;
						///
						seeFlagAktion = 0;
						seeFlagAktiont = 0;
						seeFlagAktionNew = "0";
						
						String gbegin_s = begin_seedate;
						String gbegin_d = begin_date;
						String gend_d = end_date;
						
						if (gbegin_s == null) {
							gbegin_s = "";
						}
						if (gbegin_d == null) {
							gbegin_d = "";
						}
						if ((gbegin_s.equals("")) & !(gbegin_d.equals(""))) {
							gbegin_s = gbegin_d;
						}	
						if (!(gbegin_s.equals("")) & (gbegin_d.equals(""))) {
							gbegin_d = gbegin_s;
						}
						
						if (!(gbegin_s.equals("")) & !(gbegin_d.equals(""))) {
							
							try {
								if ((setDateToString(gbegin_d).getTimeInMillis() - setDateToString(gbegin_s).getTimeInMillis()) <= 0) {
									gbegin_s = gbegin_d;	
								}
							} catch (ParseException e) {
								
							}
						}
						if ((gbegin_s.equals("")) & (gbegin_d.equals(""))) {
							seeFlagAktion = 0;
							seeFlagAktiont = 0;
						}
						
						//gbegin_d
								try {
									if (gbegin_d.equals("")){
										seeFlagAktion = 0;
										seeFlagAktiont = 0;
									} else if (dateOS().getTimeInMillis() >= setDateToString(gbegin_d).getTimeInMillis()) {
											seeFlagAktion = 1;
											seeFlagAktiont = 1;
									} else {
											seeFlagAktion = 0;
											seeFlagAktiont = 1;
									}
								} catch (ParseException e) {
									seeFlagAktion = 0;
									seeFlagAktiont = 1;
								}
						//gbegin_s
								try {
									if (gbegin_s.equals("")){
										seeFlagAktion = 0;
										seeFlagAktiont = 0;
									} else if (dateOS().getTimeInMillis() >= setDateToString(gbegin_s).getTimeInMillis()){
											seeFlagAktion = 1;
											seeFlagAktiont = 1;
											if (dateOS().getTimeInMillis() <= (setDateToString(gbegin_d).getTimeInMillis() + 86399000)) {
											seeFlagAktionNew = "1";
											}
									} else {
											seeFlagAktion = 0;
											seeFlagAktiont = 0;
									}
								} catch (ParseException e) {
									seeFlagAktion = 0;
									seeFlagAktiont = 0;
								}			
								//gend_date
								try {
									if (gend_d != null) {
										if (gend_d.equals("") & (seeFlagAktiont == 1)){
											seeFlagAktion = 1;
										} else if ((dateOS().getTimeInMillis() <= (setDateToString(gend_d).getTimeInMillis() + 86399000)) & (seeFlagAktiont == 1)) {
												seeFlagAktion = 1;
										} else {
												seeFlagAktion = 0;
										}
										
									} else {
										seeFlagAktion = 0;
									}
								} catch (ParseException e) {
									seeFlagAktion = 0;
								}
						///
						if (seeFlagAktion == 1) {		
						dgv.put("gbegin_seedate", begin_seedate);
						dgv.put("gbegin_date", begin_date);
						dgv.put("gend_date", end_date);
						dgv.put("gaction_pic", action_pic);
						dgv.put("gaction_new", seeFlagAktionNew);
						dgv.put("gfilepicPathUrl", filepicPathUrl);
						dgv.put("gmessage", parserflurl.nextText());
						dataAktions.add(dgv);
						}
	
					}
					parserflurl.next();
				}
				xmlmgurl.close(); 
				adapterAktions = new GalleryAdapter(getApplicationContext(), dataAktions);
				adapterAktions.notifyDataSetChanged();
				
			}
			catch (Throwable t) {
				
			}
			////end get data url
	   		
	   	}
	}		
	protected void ProgressGTask() {

		gdtask.setCancelable(false);
		gdtask.setMessage(getString(R.string.tdm_app));	   
		gdtask.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		gdtask.show();

	}
	private boolean isNetworkAvailable() { 
		boolean available = false; 
		ConnectivityManager myConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
		NetworkInfo networkInfo = myConnMgr.getActiveNetworkInfo(); 
		if (networkInfo != null && networkInfo.isConnected()) 
			available = true; 
		return available; 
	}
	public boolean onCreateOptionsMenu(Menu menu) { 

		getSupportMenuInflater().inflate(R.menu.pmenu, menu);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) { 
		menu.findItem(R.id.loaditem1).setEnabled(true);
		menu.findItem(R.id.pitem2).setEnabled(true);
		menu.findItem(R.id.abitem3).setEnabled(true);
		return super.onPrepareOptionsMenu(menu);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) { 
			case android.R.id.home:
				finish();			
				break;
			case R.id.loaditem1:
				GoMain();
				break; 
			case R.id.pitem2:
				//���������
				try {
					Intent Preferintent = new Intent(getApplicationContext(),PreferAmidoriya.class);
					startActivityForResult(Preferintent,0);
				} catch (Exception e) {

				}
				break; 
			case R.id.abitem3: 
				//� ���������
				try {
					Intent intentapp = new Intent(getApplicationContext(), Aboutapp.class);
					startActivityForResult(intentapp,0);
				} catch (Exception e) {

				}
				break;
		}    


		return super.onOptionsItemSelected(item); 

	} 
	
	private void GoMain() {
		AlertDialog.Builder buildergomain = new AlertDialog.Builder(this);
		buildergomain.setTitle(R.string.lt_app);		
		buildergomain.setMessage(R.string.lmmm_app);		
		buildergomain.setNegativeButton(R.string.qn_app, null);
		buildergomain.setPositiveButton(R.string.qy_app, new OnClickListener() {
				public void onClick(DialogInterface arg0, int arg1) {
					setResult(7);
					finish(); 	            	

				}
			}).create().show();	
	}
	private Calendar setDateToString(String sd) throws ParseException {
		
	      SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
	      Date date = format.parse(sd);
		  Calendar calendar = Calendar.getInstance();
		  calendar.setTime(date);
		  return calendar;
		  
		}
		
		private Calendar dateOS(){
			Calendar calendarOS = Calendar.getInstance();
			return calendarOS;
		}	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 7) {
			setResult(7);
			finish();
		}
		if (resultCode == 13) {
			setResult(13);
		}
		//����� ��� �� �������� �������� � � ���������
		if (resultCode ==  5) {
			try {
				openOptionsMenu();
			} catch (Exception e) {

			}
		}
		if (resultCode ==  9) {
			try {
				Intent Preferintent = new Intent(getApplicationContext(),PreferAmidoriya.class);
				startActivityForResult(Preferintent,0);
			} catch (Exception e) {

			}
		}
		if (resultCode ==  10) {
			try {
				Intent intentapp = new Intent(getApplicationContext(), Aboutapp.class);
				startActivityForResult(intentapp,0);
			} catch (Exception e) {

			}
		}

	}
}
